package sun.cn.common.cacheDto.utils;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

/**
 * @author sunlingao
 * @title 序列化工具类
 * @date 2017年7月6日
 * @version
 */
public final class SerializeUtils {

    private static final Logger LOG = LoggerFactory.getLogger(SerializeUtils.class);

    private SerializeUtils(){}

    public static byte[] toBytes(Object obj) {
        if (obj == null) {
            return null;
        }
        Kryo kryo = new Kryo();
        kryo.setReferences(false);

        Output output = null;

        byte[] objBytes = null;
        try {
            OutputStream out = new ByteArrayOutputStream();
            output = new Output(out);

            kryo.writeClassAndObject(output, obj);
            objBytes = output.toBytes();
        } catch (Exception e) {
            LOG.error("serializeUtils toBytes error msg is {}",e);
        } finally {
            if (output != null) {
                output.close();
            }
        }
        return objBytes;
    }

    public static Object toObject(byte[] bs) {
        if (bs == null) {
            return null;
        }
        Input input = null;
        Object obj = null;
        try {
            Kryo kryo = new Kryo();
            kryo.setReferences(false);

            kryo.setRegistrationRequired(false);
            input = null;
            input = new Input(new ByteArrayInputStream(bs), 10);
            obj = null;
            obj = kryo.readClassAndObject(input);
        } catch (Exception e) {
            LOG.error("serializeUtils toObject error msg is {}",e);
        } finally {
            if (input != null) {
                input.close();
            }
        }
        return obj;
    }

}
